import React, {Fragment} from 'react';
import {connect} from 'dva'
import {Page} from 'components'
import PageHeaderLayout from 'components/Layout/PageHeaderLayout'
import {
  Row,
  Col,
  Form,
  Radio,
  Button,
  Card,
  Icon,
  message,
  InputNumber,
  Select
} from 'antd'
import LwjTrees from 'components/LwjTree'
import GeneralFilter from 'components/Filter/GeneralFilter'
import LwjTable from 'components/LwjTable/LwjTable'
import style from './index.less'
import {Link} from 'dva/router'

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
let timer = null;
const Option = Select.Option;
const cartLists = ({location, dispatch, cartList, mydistributor, loading}) => {

  const {
    productsList,
    totalChannelPrice,
    totalRetailPrice,
    totalPrice,
    count,
    selectedRowKeys,
    selectedRows,
    selectedDistributorId
  } = cartList;

  const {
    distributorList
  } = mydistributor;

  // 面包屑
  const breadcrumbList = [
    {
      title: '分销市场',
    }, {
      title: '分销市场',
      href: '/salesmarket/salesmarket'
    }, {
      title: '购物车'
    }
  ];

  // 列表相关
  const listProps = {
    dataSource: productsList,
    loading: loading.effects['cartList/query'],
    pageChangeAction: 'cartList/query',
    dispatch,
    rowSelection:{
      selectedRowKeys: selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        dispatch({
          type: 'cartList/setSelectedRowKeys',
          selectedRowKeys: selectedRowKeys,
          selectedRows: selectedRows
        })
      },
      getCheckboxProps: item => ({
        disabled: !item.status
      })
    },
    location,
    locale:{
      emptyText:"您的购物车是空的"
    }
  }
  
  const productsColumns = [
    {
      title: '商品信息',
      dataIndex: 'productInfo',
      key: 'productInfo',
      width: '45%',
      render: (text, record, index) => (
        <div style={{ width: '100%' }}>
          <div className={style.pitem}>
            <img src={record.coverPath} className={style.pitemImg} />
            <h4 className={style.ph3}>{record.commodityName}</h4>
          </div>
        </div>
      )
    }, {
      title: '零售价￥',
      dataIndex: 'price',
      key: 'price',
      width: '15%',
      render: (text, record, index) => (
        <div style={{ width: '100%' }}>
          <div className={style.pitem}>
             {record.price}
          </div>
        </div>
      )
    }, {
      title: '渠道价￥',
      dataIndex: 'channelPrice',
      key: 'channelPrice',
      width: '15%',
      render: (text, record, index) => (
        <div style={{ width: '100%' }}>
          <div className={style.pitem}>
             {record.channelPrice}
          </div>
        </div>
      )
    }, {
      title: '数量',
      dataIndex: 'number',
      key: 'number',
      width: '15%',
      render: (text, record, index) => (
        <div style={{ width: '100%' }}>
          <div className={style.pitem}>
            <InputNumber min={1} max={999} value={record.number} onChange={(value) => {updateCount(record, index, value+'')}} />
          </div>
        </div>
      )
    }, {
      title: '操作',
      dataIndex: 'handleType',
      key: 'handleType',
      width: '10%',
      render: (text, record, index) => (
        <span>
          <a onClick={() => deleteProducts([record])}>删除</a>
        </span>
      )
    }
  ]

  // 删除
  const deleteProducts=(items)=>{
    if(!items || (items && items.length == 0)){
      message.error("请选择要删除的商品");
      return;
    }
    dispatch({
      type: 'cartList/deleteProducts',
      items
    })
  }

  // 数量减
  const updateCount=(item, index, count)=>{
    count = count.replace(/\D/g,'');
    if(!count || (count == '') || (count == '0')){
      count = 1;
    }
    if(count && count > 999){
      count = 999;
    }
    productsList[index].number = parseInt(count);
    dispatch({
      type: 'productsList/success',
      productsList
    })
    clearTimeout(timer);
      timer = setTimeout(function(){
      dispatch({
        type: 'cartList/updateCount',
        index,
        id: item.id,
        count: parseInt(count)
      })
    },500)
  }

  //去结算
  const goCartCaluate=()=>{
    if(!selectedRowKeys || (selectedRowKeys && selectedRowKeys.length == 0)){
      message.error("请选择待结算的商品");
      return;
    }
    if(selectedRowKeys && selectedRowKeys.length > 50){
      message.error("选择的商品种类超过50种，建议分批结算！");
      return;
    }
    let _temp = [];
    dispatch({
      type: 'cartList/goCartCaluate',
      selectedRowKeys
    })
  }

  const handleDistributorChange = (val) => {
    dispatch({
      type: 'cartList/changeDistributor',
      selectedDistributorId: val
    })
    dispatch({
      type: 'cartList/query'
    })
  }


  return (
    <PageHeaderLayout title="购物车" breadcrumbList={breadcrumbList}>
      <div className={style.distributor}>
        <div className={style.label}>当前门店</div>
        <Select
          defaultValue={selectedDistributorId}
          onChange={handleDistributorChange}
          showSearch
          filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
          className={style.selectBox}
          dropdownClassName={style.dropDownBox}
        >
          <Option key='-1'>请选择</Option>
          {distributorList.map((distributor) => <Option key={distributor.id}>{distributor.name}</Option>)}
        </Select>
      </div>
      <Page inner>
        <Row>
          <Link className={style.backLink} to={selectedDistributorId ? '/salesmarket/salesmarket?id='+selectedDistributorId : '/salesmarket/salesmarket'}>返回分销市场</Link>
          <Button className={style.delBtn} onClick={() => {deleteProducts(selectedRows)}}>批量删除</Button>
        </Row>
        <LwjTable {...listProps} columns={productsColumns} pagination={false}/>
        <Row className={style.price}>
            <Col span={4}offset={12}>
                <p>渠道提货总价</p>
                <p className={style.jiage}>{totalChannelPrice}</p>
            </Col>
            <Col span={4}>
                <p>建议零售总价</p>
                <p className={style.jiage}>{totalRetailPrice}</p>
            </Col>
            <Col span={4}>
                <p>商品总数</p>
                <p className={style.jiage}>{count}</p>
            </Col>              
            <Col span={24} className={style.totalprice}>                  
            </Col> 
            <Col span={4} offset={20}>
              <p>总价</p>
              <p className={style.jiage}>{totalPrice}</p>
            </Col>               
        </Row>
        <Row>
          <Col span={4} offset={20} className={style.jiesuan}>
            <Button type='primary' onClick={goCartCaluate}>去结算</Button>
          </Col>            
        </Row>
      </Page>
    </PageHeaderLayout>
  )
};

export default connect(({cartList, mydistributor, loading}) => ({cartList, mydistributor, loading}))(cartLists)
